<?php
/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 2019/12/4
 * Time: 10:31
 */
namespace app\api;

use app\BaseController;

abstract class ApiController extends BaseController
{

    // 初始化
    protected function initialize()
    {
        parent::initialize();
        $class = is_object($this) ? get_class($this) : $this;
        $pace = str_replace('\\', '/', $class);
        $classname = basename($pace) ;
        $validata_namespace = str_replace('/','\\','/'.dirname(dirname($pace)).'/validate/');
//        实例化对应模型
        $this->newModel('\app\api\model\\'.$classname);
//        自动验证字段
        $this->autoValidata($validata_namespace.$classname);
        dump('api-initialize');
    }
    /**
     * 实例化对应模型
     * @param $classname    类名
     */
    protected function newModel($classname){
        $this->model = new $classname();
    }

    /**
     * 自动验证
     * @param $classname
     */
    protected function autoValidata($classname){
        $validata = new $classname();
        $result = $validata ->check($this->request->data);
        if(!$result){
            $this->error($validata->getError());
        }
    }


    /**
     * api成功返回
     * $code    0正常，101提示+正常使用,102弹出+正常使用
     */
    protected function success($data,$code=0,$msg=''){
        $res = [
            'code' => $code,
            'data' => $data,
            'msg'  => $msg,
            'time' => $_SERVER['REQUEST_TIME'],
            'wait' => 3
        ];
        die(json_encode($res));
    }

    /**
     * api失败返回
     * $code    1000操作失败,1001签名错误,1002参数错误,1004登录过期,1005请求超时
     */
    protected function error($msg='请求错误',$code=1002){
        $res = [
            'code' => $code,
            'msg'  => $msg,
            'time' => $_SERVER['REQUEST_TIME'],
            'wait' => 3
        ];
        die(json_encode($res));
    }
}